<template>
<el-container style="height: 700px; border: 1px solid #eee">
  <!--头部-->
  <el-header style=" font-size: 40px; background-color: rgb(37, 108, 155); color: #eee; line-height: 60px;">
     101工作日志管理系统
  </el-header>
  <el-container>
    <!--侧边栏-->
    <el-aside width="150px" style="border: 1px solid #eee">
      <!--菜单-->
      <el-menu>
        <el-menu-item index="1">
          <i class="el-icon-menu"></i>
          <router-link to="log"  class="no-link-style">问题记录</router-link>
        </el-menu-item>
        <el-menu-item index="2">
          <i class="el-icon-menu"></i>
          <router-link to="utils" class="no-link-style">常用工具</router-link>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <!--主体-->
    <el-main>
      <!--搜索框-->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline"> 
        <el-form-item label="标题"> 
        <el-input v-model="searchForm.name" placeholder="问题标题"></el-input>
        </el-form-item> 
        <el-form-item label="问题类别"> 
          <el-select v-model="searchForm.problem_type" placeholder="问题类别"> 
            <el-option label="无选择" value=""></el-option> 
            <el-option label="信息化异常" value="信息化异常"></el-option> 
            <el-option label="生产协调" value="生产协调"></el-option>
          </el-select>
        </el-form-item> 
        <el-form-item> 
          <el-button type="primary" @click="onSubmit" style="background-color: rgb(37, 108, 155);">查询</el-button>
        </el-form-item>
        <!-- 创建弹窗按钮 -->
        <create-dialog-view :table-data="tableData" @handleCreateEvent="handleCreate"></create-dialog-view>
      </el-form>
      <!--表格-->
      <el-table
      :data="tableData"
      stripe
      style="width: 100%">
      <el-table-column
      prop="name"
      label="问题标题"
      width="130">
      </el-table-column>
      <el-table-column prop="date" label="发生日期" width="130">
        <template slot-scope ="scope">
            <span>{{formatDate2(scope.row.date)}}</span>
        </template>
      </el-table-column>
    <el-table-column
      prop="region_name"
      label="相关班组"
      width="100">
    </el-table-column>
    <el-table-column
      prop="problem_type"
      label="问题分类"
      width="100">
    </el-table-column>
    <el-table-column
      prop="description"
      label="详细描述"
      width="200">
    </el-table-column>
    <el-table-column
      prop="solution"
      label="解决方案思路"
      width="280">
    </el-table-column>
    <el-table-column label="操作" width="250">
      <template slot-scope="scope">
        <el-button style="background-color: rgb(37, 108, 155);" type="primary" size="mini" @click="callEditFormViewMethod(scope.$index)">编辑</el-button>
        <el-button style="background-color: rgb(37, 108, 155);" type="primary" size="mini" @click="showDelDialog(scope.$index)">删除</el-button>
        <el-button style="background-color: rgb(37, 108, 155);" type="primary" size="mini" @click="showUploadDialog(scope.row.log_id)">上传</el-button>
      </template>
    </el-table-column>
    <el-table-column
    prop="diagram"
    label="因果图"
    width="210">
      <template slot-scope="scope">
        <el-image 
        style="width: 150px;height: 100px;"
        :src="scope.row.diagram"
        :headers="{'Authorization': 'Bearer ' + token}  "
        :preview-src-list=[scope.row.diagram]
        @click="vbs(scope.row.diagram)"
        >
          <div slot="error" class="image-slot">
            <span>请上传因果图</span>
          </div>
        </el-image>
      </template>  
  </el-table-column>
    <el-table-column prop="updatetime" label="操作时间" width="200">
      <template slot-scope = "scope">
        <span>{{ formatDate(scope.row.updatetime) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="is_solved" label="解决状态" width="80">
      <template slot-scope = "scope">
         <span v-if = "scope.row.is_solved === true" >
          <el-button type="success" icon="el-icon-check" circle></el-button>
        </span>
        <span v-if = "scope.row.is_solved === false" >
          <el-button type="warning" icon="el-icon-star-off" circle></el-button>
        </span>
    </template>
    </el-table-column>
      </el-table>
      <!--弹窗编辑-->
      <edit-dialog-view :table-data="tableData" @handleEditEvent="handleEdit" ref="edit-dialog-view"></edit-dialog-view>
      <!--弹窗删除-->
      <DeleteDialogView  @confirm-delete="handleDelete" ref="delete-dialog-view"></DeleteDialogView>
      <!--上传因果图-->
      <UploadDialogView :logId="logId" @upload-success="handleUploadSuccess" ref="upload-dialog-view"></UploadDialogView>
      <!--分页-->
      <el-pagination
      background
      :page-size="pageSize"
      :current-page="page"
      :total="total"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      layout="sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
      </el-pagination>
    </el-main>
  </el-container>
</el-container>
</template>
<script>
import Vue from 'vue';
import moment from 'moment';
import CreateDialogView from './components/CreateDialogView.vue';
import EditDialogView from './components/EditDialogView.vue';
import DeleteDialogView from './components/DeleteDialogView.vue';
import UploadDialogView from './components/UploadDialogView.vue'
export default{
  components: { CreateDialogView, EditDialogView,DeleteDialogView,UploadDialogView},
  data() {
    return {
      token:localStorage.getItem('token'),
      // 上传因果图的logId
      logId:0,
      // 因果图预览
      srcList: [
          'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
          'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
        ],
      // 删除的表格行号
      delIndex:0,
      // 数据源
      tableData: [],
      // 搜索框
      searchForm:{
        problem_type:'',
        name:''
        },
      dialogTableVisible: false,
      formLabelWidth: '120px',
      page: 1, // 当前页码，初始化为1
      pageSize: 5, // 每页显示的数量，这里设置为5
      total:100
      }
    },
  methods:{
      // 用于获取数据的方法，根据分页参数
      fetchData() {
        console.log("/page")
        this.$axios.get('/page', {
            params: {
                page: this.page,
                pageSize: this.pageSize,
                problem_type: this.searchForm.problem_type,
                name: this.searchForm.name
            }
        }).then(resp => {
            console.log("成功获取resp.data.data",resp.data.data.rows)
            this.tableData = resp.data.data.rows;
        }).catch((error)=>{
          console.log(error)
        });
        },
        // 整理时间格式
        formatDate(dateStr) {
          return moment(dateStr).format('YYYY-MM-DD HH:mm:ss');
        },
        formatDate2(dateStr) {
          return moment(dateStr).format('YYYY-MM-DD');
        },
        // 当前页最大数量
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`);
          this.pageSize = val;
          this.fetchData();
        },
        // 当前页变化
        handleCurrentChange(val) {
          console.log(`当前页: ${val}`);
          this.page = val;
          this.fetchData();
        },
        // 条件查询日志
        onSubmit() {
          console.log("执行条件查询");
          this.fetchData();
        },
        // 新建日志
        handleCreate(createdItem) {
          console.log("执行创建");
          this.$axios.post("/addlog", createdItem)
          .then((response) => {
            // 处理成功的响应
            console.log('创建成功，服务器响应:', response.data);
            createdItem.updatetime = response.data.data.updatetime;
            // 将新创建的项目添加到表格数据中
            // this.tableData.push(createdItem);
            this.fetchData();
          })
          .catch((error) => {
            // 处理错误
            console.error('创建失败，错误信息:', error);
          });
        },

        // 调用子组件方法，并在父组件传入参数
        callEditFormViewMethod(index){
          this.$refs['edit-dialog-view'].openEditDialog(index);
        },
        // 编辑日志
        handleEdit(editedItem,index){
          console.log("执行了编辑")
          this.$axios.put("/editlog",editedItem).then((resp)=>{
            console.log( resp.data.data)
            Vue.set(this.tableData,index,resp.data.data)
            console.log(this.tableData[index].is_solved)
          }).catch((error) => {
            console.error('编辑失败，错误信息:', error);
        });
        },
        // 显示删除弹窗
        showDelDialog(index){
          this.delIndex = index;
          this.$refs['delete-dialog-view'].deletedialogVisible = true;
        },
        handleUploadSuccess(){
          this.fetchData();
        },
        // 显示上传弹窗
        showUploadDialog(logId){
          console.log("log_id为",logId)
          this.logId=logId
          console.log("this.logId为",this.logId)
          this.$refs['upload-dialog-view'].uploadDialogVisible = true;
        },
        // 删除日志
        handleDelete() {
              const index = this.delIndex;
              console.log("执行删除日志")
              const log = this.tableData[index];
              console.log("获取的当前日志：",log)
              const params = {
                description: log.description,
                is_solved: log.is_solved,
                name: log.name,
                solution: log.solution
              }
           // 将获取log_id的操作改为返回Promise的形式
          this.$axios.get('/getlogid', {
            params: params
          }).then(resp => {
          this.tableData[index].log_id = resp.data.data;
          console.log("logId:", this.tableData[index].log_id);
          const logId = this.tableData[index].log_id;
          // 正确使用模板字符串
          return this.$axios.delete(`/deletelog/${logId}`);
        }).then(() => {
          // 在删除成功的回调中执行splice操作
          // this.tableData.splice(index, 1);
          this.fetchData();
        }).catch((error) => {
          console.error('删除失败，错误信息:', error);
        });
      }
    },
  mounted(){
    /*
  axios.get("http://localhost:1013/list")
        .then(resp=>{
          this.tableData=resp.data.data; //响应数据赋值给数据模型
        });
      }*/
     this.fetchData();
     // 检查数据源内容
     console.log("初始数据源："+this.tableData);
    }
    }
</script>
<style>
        .no-link-style { 
        text-decoration: none; 
        color: inherit;
       }
      .image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px; /* 这里的高度要和el - image的高度一致 */
}
</style>

